package mao.concurent.consumer;



import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Totoro
 * @date 2020/7/8
 * @explain:
 */
public class Consumer<T> implements Runnable {
    public MyConcurrentQueue<T> queue;
    private static AtomicInteger count = new AtomicInteger(0);
    private static Random random = new Random(47);
    private int id = count.incrementAndGet();

    public Consumer(MyConcurrentQueue<T> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            T t = queue.get();
            if (null != t){
                try {
                    TimeUnit.SECONDS.sleep(random.nextInt(10));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                System.out.println(this+"consume"+t);
            }else {
                System.out.println(this+"消费失败");
            }
        }
    }

    @Override
    public String toString() {
        return "Consumer{" +
                "id=" + id +
                '}';
    }
}
